package br.com.players.service;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import org.hibernate.Session;

import br.com.players.model.PlayerDefaultEntity;

public class PlayersService {
	
	protected EntityManager em = EntityManagerFactoryHelper.getEntityManager();
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	protected  Object find(Class clazz, Serializable primaryKey) {
		return em.find(clazz, primaryKey);
	}
	
	@SuppressWarnings("rawtypes")
	protected List findAll(Class clazz) {
		return ((Session) em.getDelegate()).createCriteria(clazz).list();
	}
	
	protected void persist(Object object) {
		EntityTransaction tx = null;
		
		try {
			
			tx = em.getTransaction();
			
			tx.begin();
			
			em.persist(object);
			em.flush();
			
			tx.commit();
			
		} catch (RuntimeException re) {
            if (tx != null && tx.isActive()) tx.rollback();

	        throw re;
	    } 
	}
	
	protected void update(PlayerDefaultEntity entity) {
		EntityTransaction tx = null;
		
		try {
			
			tx = em.getTransaction();
			
			tx.begin();
			em.merge(entity);
			em.flush();
			
			tx.commit();
			
		} catch (RuntimeException re) {
            if (tx != null && tx.isActive()) tx.rollback();

	        throw re;
	    } catch (Exception exception) {
	    	throw new RuntimeException();
	    }
	}
	
	protected void remove(PlayerDefaultEntity entity) {
		EntityTransaction tx = null;
		
		try {
			tx = em.getTransaction();
			
			tx.begin();
			Object attachedEntity = em.find(entity.getClass(), entity.getId());
			em.remove(attachedEntity);
			em.flush();
			
			tx.commit();
			
		} catch (RuntimeException re) {
            if (tx != null && tx.isActive()) tx.rollback();

	        throw re;
	    } catch (Exception ex) {
	    	throw new RuntimeException();
	    }
	}
}